#include "blockingqueue.hpp"
#include "Task.hpp"
#include <ctime>
#include <string>
#include <sys/types.h>
#include <unistd.h>

using namespace std;

pthread_mutex_t cout_lock = PTHREAD_MUTEX_INITIALIZER;

const string oper = "+-*/%";

int mymath(int x, int y, char op)
{
    int result;
    switch (op)
    {
    case '+':
        result = x + y;
        break;
    case '-':
        result = x - y;
        break;
    case '*':
        result = x * y;
        break;
    case '/':
    {
        if (y == 0)
        {
            cerr << "div zero fault!" << endl;
            result = -1;
        }
        else
            result = x / y;
    }
    break;
    case '%':
    {
        if (y == 0)
        {
            cerr << "mod zero fault!" << endl;
            result = -1;
        }
        else
            result = x % y;
    }
    break;
    default:
        break;
    }

    return result;
}

void *productor(void *args)
{
    BlockQueue<Task> *bq = static_cast<BlockQueue<Task> *>(args);

    while (true)
    {
        // 生产活动
        int x = rand() % 500 + 1;                   // 1 - 500
        int y = rand() % 200;                       // 0 - 200
        int oper_index = rand() % oper.size();      // 0 - 4
        Task t(x, y, oper[oper_index], mymath);

        bq->push(t);

        pthread_mutex_lock(&cout_lock);
        cout << "生产任务 : " << t.task_to_string() << endl;
        pthread_mutex_unlock(&cout_lock);

        // sleep(1);
    }

    return nullptr;
}

void *consumer(void *args)
{
    BlockQueue<Task> *bq = static_cast<BlockQueue<Task> *>(args);

    while (true)
    {
        // 消费活动
        Task t;
        bq->pop(&t);

        pthread_mutex_lock(&cout_lock);
        cout << "消费任务 : ";
        cout << t() << endl;
        pthread_mutex_unlock(&cout_lock);

        sleep(1);
    }

    return nullptr;
}

int main()
{
    srand((unsigned int)time(nullptr) ^ getpid() ^ 2024);

    BlockQueue<Task> *bq = new BlockQueue<Task>();

    pthread_t c1, c2, c3, p1, p2, p3;

    pthread_create(&p1, nullptr, productor, bq);
    // pthread_create(&p2, nullptr, productor, bq);
    // pthread_create(&p3, nullptr, productor, bq);
    pthread_create(&c1, nullptr, consumer, bq);
    // pthread_create(&c2, nullptr, consumer, bq);
    // pthread_create(&c3, nullptr, consumer, bq);

    pthread_join(c1, nullptr);
    // pthread_join(c2, nullptr);
    // pthread_join(c3, nullptr);
    // pthread_join(p1, nullptr);
    // pthread_join(p2, nullptr);
    // pthread_join(p3, nullptr);

    delete bq;
    return 0;
}